package tree;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 树
 */
public class Solution {
    Map<Integer, Integer> indexMap = new HashMap<>();

    /**
     * 106. 从中序与后序遍历序列构造二叉树
     * @param inorder
     * @param postorder
     * @return
     */
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            indexMap.put(inorder[i], i);
        }

        return findNode(inorder, 0, inorder.length - 1, postorder, postorder.length - 1);
    }

    private TreeNode findNode(int[] inorder, int inStart, int inEnd, int[] postorder, int postEnd) {
        if (inStart > inEnd) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[postEnd]);

        int index = indexMap.get(postorder[postEnd]);

        root.left = findNode(inorder, inStart, index - 1, postorder, postEnd - (inEnd - index) - 1);
        root.right = findNode(inorder, index + 1, inEnd, postorder, postEnd - 1);

        return root;
    }

    public static long prev = Long.MIN_VALUE;
    public static boolean isValidBST(TreeNode root) {
        if(root == null){
            return true;
        }
        if(!isValidBST(root.left)){
            return false;
        }
        if(root.val <= prev){
            return false;
        }
        prev = root.val;
        return isValidBST(root.right);
    }

    /**
     * 701. 二叉搜索树中的插入操作
     * @param root
     * @param val
     * @return
     */
    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        }

        if (val < root.val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }

        return root;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(1);
        root.left.right = new TreeNode(9);
        root.right = new TreeNode(6);
        root.right.left = new TreeNode(3);
        System.out.println(isValidBST(root));
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
